package cn.zn.modules.invoice.service.impl;

import cn.zn.framework.common.utils.PageUtils;
import cn.zn.modules.invoice.dao.InvoiceDetailDao;
import cn.zn.modules.invoice.entity.InvoiceDetailEntity;
import cn.zn.modules.invoice.entity.InvoiceDetailRecord;
import cn.zn.modules.invoice.entity.dto.InvoiceDetailQueryDTO;
import cn.zn.modules.invoice.service.InvoiceDetailRecordService;
import cn.zn.modules.invoice.service.InvoiceDetailService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;


@Service("invoiceDetailService")
public class InvoiceDetailServiceImpl extends ServiceImpl<InvoiceDetailDao, InvoiceDetailEntity> implements InvoiceDetailService {

    @Autowired
    private InvoiceDetailRecordService invoiceDetailRecordService;

    @Override
    public PageUtils queryPage(InvoiceDetailQueryDTO invoiceDetailQuery) {
        IPage page = new Page(invoiceDetailQuery.getOffset() / invoiceDetailQuery.getLimit() + 1, invoiceDetailQuery.getLimit());
        List<InvoiceDetailEntity> list = this.baseMapper.queryPage(invoiceDetailQuery.getRecordCode(), page);
        page.setRecords(list);
        return new PageUtils(page);
    }

    @Override
    public List<InvoiceDetailEntity> queryList(String recordCode) {
        return this.baseMapper.queryPage(recordCode, null);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteByRecordCode(String recordCode) {
        List<Long> invoiceDetailIds = invoiceDetailRecordService.list(new QueryWrapper<InvoiceDetailRecord>()
                .eq("record_code", recordCode)).stream().map(InvoiceDetailRecord::getInvoiceId).collect(Collectors.toList());
        if(!invoiceDetailIds.isEmpty()){
            this.baseMapper.deleteBatchIds(invoiceDetailIds);
        }
    }

    @Override
    public boolean save(InvoiceDetailEntity entity) {
        super.save(entity);
        this.baseMapper.insertRecord(entity.getId(), entity.getRecordCode());
        return true;
    }
}